# coding = utf-8
from PIL import Image
from django.http import JsonResponse, HttpResponse
from QipaoProject.classifies import mainCL as CL
from QipaoProject.classifies import classify as clf
from QipaoProject.classifies import variable as va
from QipaoProject.classifies import hogfeature as hog
import json
'''
================

    支持函数
    
================

'''
# 获取模型的参数设置与性能
def get_model_cfg(clf_type):
    f = open(va.model_path + clf_type + '_cfg.txt', 'r')
    text = f.readlines()
    # 组装结果
    result = {}
    # 获取第1个参数
    t = text[0].split('\t')
    result[t[0]] = t[1][:-1]
    # 获取第2个参数
    t = text[1].split('\t')
    result[t[0]] = t[1][:-1]
    # 获取第3个参数
    t = text[2].split('\t')
    result[t[0]] = t[1][:-1]
    # 获取训练图片总数
    t = text[3].split('\t')
    result['train_num'] = t[1][:-1]
    # 获取训练时间
    t = text[4].split('\t')
    result['train_time'] = t[1][:-1]
    # 获取测试时正确分类的数量
    t = text[5].split('\t')
    result['correct'] = t[1][:-1]
    # 获取测试图片总数
    t = text[6].split('\t')
    result['total'] = t[1][:-1]
    # 获取测试的正确率
    t = text[7].split('\t')
    result['rate'] = t[1][:-1]
    # 获取测试时间
    t = text[8].split('\t')
    result['test_time'] = t[1][:-1]
    f.close()
    return result

'''
================

    API函数

================

'''
# 图片上传
def upload(request):
    # 接收图片的数据
    data = request.FILES['image']
    # 转为图片
    image = Image.open(data)
    image.save('media/images/' + data.name)
    data = [{
        'code':0,
        'msg': '',
        'data':{'src': 'media/images/' + data.name}
    }]
    return JsonResponse(data, safe = False)

# 进行分类
def doclassify(request):
    # 接收要识别的图片路径
    img_url = request.GET.get('img_url')
    # 默认使用SVM模型进行分类
    clf_type = request.GET.get('choose')
    result = None
    # 根据分类器的类型来调用不同的模型进行分类
    if clf_type == 'SVM':
        result = clf.do_SVM_Classify(img_url)
    elif clf_type == 'KNN':
        result = clf.do_KNN_Classify(img_url)
    elif clf_type == 'RF':
        result = clf.do_RF_Classify(img_url)
    # 返回分类结果
    return HttpResponse(va.labels[int(result)])

# 训练SVM模型
def build_SVM(request):
    C = None
    kernel = None
    gamma = None
    if request.POST:
        C = request.POST.get('svm_C', 1)
        kernel = request.POST.get('svm_kernel', 'rbf')
        gamma = request.POST.get('svm_gamma', 1.2)

    else:
        C = request.GET.get('svm_C', 1)
        kernel = request.GET.get('svm_kernel', 'rbf')
        gamma = request.GET.get('svm_gamma', 1.2)
    # 组装参数
    args = {}
    args['C'] = float(C)
    args['kernel'] = kernel
    args['gamma'] = float(gamma)
    # 训练模型
    result = CL.train_model('SVM', args)
    res = str(result)
    return HttpResponse(res)

# 训练KNN模型
def build_KNN(request):
    n_neighbors = None
    weight = None
    algorithm = None
    if request.POST:
        n_neighbors = request.POST.get('knn_n_neighbors', 1)
        weight = request.POST.get('knn_weight', 'uniform')
        algorithm = request.POST.get('knn_algorithm', 'auto')
    else:
        n_neighbors = request.POST.get('knn_n_neighbors', 1)
        weight = request.POST.get('knn_weight', 'uniform')
        algorithm = request.POST.get('knn_algorithm', 'auto')
        
    # 组装参数
    args = {}
    args['n_neighbors'] = int(n_neighbors)
    args['weight'] = weight
    args['algorithm'] = algorithm
    # 训练模型
    result = CL.train_model('KNN', args)
    res = str(result)
    return HttpResponse(res)

# 训练RandomForest模型
def build_RF(request):
    criterion = None
    max_depth = None
    algorithm = None
    if request.POST:
        criterion = request.POST.get('rf_criterion', 'gini')
        max_depth = request.POST.get('rf_max_depth', None)
        min_samples_leaf = request.POST.get('rf_min_samples_leaf', 1)
    else:
        criterion = request.GET.get('rf_criterion', 'gini')
        max_depth = request.GET.get('rf_max_depth', None)
        min_samples_leaf = request.GET.get('rf_min_samples_leaf', 1)
    # 处理min_samples_leaf
    if float(min_samples_leaf) < 0.6:
        min_samples_leaf = float(min_samples_leaf)
    else:
        min_samples_leaf = int(min_samples_leaf)
    # 组装参数
    args = {}
    args['criterion'] = criterion
    args['max_depth'] = int(max_depth)
    args['min_samples_leaf'] = min_samples_leaf
    # 训练模型
    result = CL.train_model('RF', args)
    res = str(result)
    return HttpResponse(res)

# 显示特征图
def show_feat_img(request):
    path = ''
    if request.POST:
        path = request.POST.get('img_path')
    else:
        path = request.GET.get('img_path')
    hog.show_feat_img(path)
    return HttpResponse('ok')

# 获取模型的参数与性能
def get_models_cfg():
    svm_result = get_model_cfg('SVM')
    knn_result = get_model_cfg('KNN')
    rf_result = get_model_cfg('RF')
    return svm_result, knn_result, rf_result
